# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import datetime

from flask import request
from werkzeug.exceptions import RequestEntityTooLarge

from ksai.models.document_attachment import DocumentAttachmentModelQuery, DocumentContext
from ksai.persistence.storage.events import app_storage_file_post_persistence
from ksai.persistence.storage.uploader import AttachmentUploader
from ksai.services.document_attachment import DocumentAttachmentService
from ksai.web.api import ApiResource
from ksai.web.exceptions import UploadSizeOverLimitedMimeException


class DocumentListController(ApiResource):

    def get(self, query=DocumentAttachmentModelQuery()):
        query.init(request.args, 15)
        DocumentAttachmentService.find_by_query(query)

        return self.make_success(result=query)

    def delete(self, uuid):
        saved = DocumentAttachmentService.find_one_by_uuid(uuid)
        saved.deleted_at = datetime.datetime.now()
        DocumentAttachmentService.save(saved)
        return self.make_success(saved)


class DocumentUpdateDeleteController(ApiResource):

    def delete(self, uuid):
        saved = DocumentAttachmentService.find_one_by_uuid(uuid)
        saved.deleted_at = datetime.datetime.now()
        DocumentAttachmentService.save(saved)
        return self.make_success(saved)


class DocumentUploaderController(ApiResource):

    def post(self):
        try:
            attachment = AttachmentUploader.upload(category="document", channel="labeler_document")
            document = DocumentAttachmentService.save_from_storage_file(attachment)

            app_storage_file_post_persistence.send(DocumentContext(attachment, document))
        except RequestEntityTooLarge:
            raise UploadSizeOverLimitedMimeException()

        return self.make_success(result=document)
